package org.example.config;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description
 * @Author 魏锴
 * @Date 2024/1/3
 */
@Configuration
@ComponentScan(basePackages = {"org.example.mapper", "org.example.service", "org.example.entity","org.example.controller"})
@MapperScan(basePackages = "org.example")
public class MybatisConfig {
    @Bean
    public SqlSessionFactory sqlSessionFactory() {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            return new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //既然有了sqlSessionFactory,顾名思义，我们就可以从中获得sqlSession的实例了
    //sqlSession 完全包含了面向数据库执行SQL命令所需的所有方法
    @Bean
    public SqlSession sqlSession() {
        return sqlSessionFactory().openSession(true);
    }

}
